package top.digger.web.cron;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import top.digger.web.entity.DataShPoint;
import top.digger.web.mapper.DataShPointMapper;

import java.io.IOException;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

@Configuration
@EnableScheduling
public class SZPointCronTask {

    protected final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    public DataShPointMapper dataShPointMapper;

    @Scheduled(cron = "0 0 1 * * ?")
    private void configureTasks() {
        HttpClient httpClient = init();
        String today = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
        String url = String.format("http://web.ifzq.gtimg.cn/appstock/app/fqkline/get?param=sh000001,day,%s,,1,qfq", today);
        logger.info("爬取的url为{}", url);
        HttpGet httpGet = get(url, null);
        try {
            HttpResponse httpResponse = httpClient.execute(httpGet);
            String result = EntityUtils.toString(httpResponse.getEntity());
            JSONObject jsonObject = (JSONObject) JSONObject.parse(result);
            JSONArray dataJsonArray = jsonObject.getJSONObject("data").getJSONObject("sh000001").getJSONArray("day");
            for (int i = 0; i < dataJsonArray.size(); i++){
                String date = dataJsonArray.getJSONArray(i).get(0).toString();
                double open = Double.parseDouble(dataJsonArray.getJSONArray(i).get(1).toString());
                double close = Double.parseDouble(dataJsonArray.getJSONArray(i).get(2).toString());
                double max = Double.parseDouble(dataJsonArray.getJSONArray(i).get(3).toString());
                double min = Double.parseDouble(dataJsonArray.getJSONArray(i).get(4).toString());
                double trade = Double.parseDouble(dataJsonArray.getJSONArray(i).get(5).toString());
                DataShPoint dataShPoint = new DataShPoint();
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                dataShPoint.setDate(sdf.parse(date));
                dataShPoint.setOpenPrice(new BigDecimal(open));
                dataShPoint.setClosePrice(new BigDecimal(close));
                dataShPoint.setMaxPrice(new BigDecimal(max));
                dataShPoint.setMinPrice(new BigDecimal(min));
                dataShPoint.setTradeNumber(new BigDecimal(trade));
                dataShPointMapper.insert(dataShPoint);
            }
        } catch (IOException | ParseException e) {
            e.printStackTrace();
        }
    }

    public HttpClient init(){
        RequestConfig requestConfig = RequestConfig.custom()
                .setConnectTimeout(5000)//一、连接超时：connectionTimeout-->指的是连接一个url的连接等待时间
                .setSocketTimeout(5000)// 二、读取数据超时：SocketTimeout-->指的是连接上一个url，获取response的返回等待时间
                .setConnectionRequestTimeout(5000)
                .build();
        CloseableHttpClient httpClient = HttpClientBuilder.create().setDefaultRequestConfig(requestConfig).build();
        return httpClient;
    }


    public HttpGet get(String url, Map<String, String> params){
        if (params != null){
            StringBuffer sb = new StringBuffer();
            for (Map.Entry<String, String> entry : params.entrySet()){
                sb.append(entry.getKey()).append("=").append(entry.getValue()).append("&");
            }
            sb.deleteCharAt(sb.length() - 1);
            url = url + "?" + sb.toString();
        }
        HttpGet httpGet = new HttpGet(url);
        return httpGet;
    }
}
